package server;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.*;

/**
 * Servlet implementation class UserServlet
 * This class provides the functionality for 
 * user login.
 * @author Spencer, Valerie
 */
public class UserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
        private FarmerHandler fhandle = new FarmerHandler();
        private static String farmerName="";
	/**
	 * Handles login. Attempts to login a user using a designated email address and password.
         * Locks the account out if login has been attempted 3 times. Returns an error message
         * if the user/password combination is invalid.
         * 
         * @param request servlet request
         * @param response servlet response
         * @throws ServletException if a servlet-specific error occurs
         * @throws IOException if an I/O error occurs
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
                Cookie[] cookies = request.getCookies();
                int lockout=0;
                for(Cookie c:cookies){
                    if (c.getName().equals("lockout")){
                        lockout=Integer.parseInt(c.getValue());
                    }
                            
                }
                if(lockout<3){
		int passHash = request.getParameter("pwd").hashCode();
		String user = request.getParameter("name");
		if (user.toLowerCase()
				.matches(
						"([_A-Za-z0-9-]+)(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[A-Za-z]{2,})")) {
                    
                    Farmer farm = fhandle.getFarmer(user);
                    if(farm==null){
                        String head=request.getHeader("Referer");
                        if(head.contains("?")){
                            head=head.substring(0, head.indexOf("?"));
                        
                        }
                        response.sendRedirect(head+"?login=noexist");
                    }else if(farm.getLockout()==true){
                        Cookie lockoutCookie = new Cookie("lockout", "0");
                        response.addCookie(lockoutCookie);
                        String head = request.getHeader("Referer");
                            if(head.contains("?")){
                                head=head.substring(0,head.indexOf("?"));
                            }
                            response.sendRedirect(head+"?login=lockedout");
                    }
                    else if (farm.getEmail().equals(user)
					&& passHash == farm.getPasshash()) {
			            Cookie userCookie = new Cookie("user", farm.getEmail());
                                     HttpSession session = request.getSession(true);
                                    session.setAttribute("user", farm.getEmail());
                                     response.addCookie(userCookie);
                                    Cookie lockoutCookie = new Cookie("lockout", "0");
                                    response.addCookie(lockoutCookie);
                                 response.sendRedirect("index.jsp");
                                
			} else {
                                String head = request.getHeader("Referer");
                                if(head.contains("?")){
                                    head=head.substring(0,head.indexOf("?"));
                                }
                                if(farmerName.equals(user) || farmerName.equals("")){
                                lockout++;
                                } else{
                                    lockout=0;
                                    farmerName=user;
                                }
                                Cookie lockoutCookie = new Cookie("lockout", Integer.toString(lockout));
                                    response.addCookie(lockoutCookie);
				response.sendRedirect(head +"?login=bad");
			}
		} else {
                            String head = request.getHeader("Referer");
                            if(head.contains("?")){
                                head=head.substring(0,head.indexOf("?"));
                                }
                            if(farmerName.equals(user) || farmerName.equals("")){
                                lockout++;
                                } else{
                                    lockout=0;
                                    farmerName=user;
                                }
                                Cookie lockoutCookie = new Cookie("lockout", Integer.toString(lockout));
                                    response.addCookie(lockoutCookie);
				
			response.sendRedirect(head+"?login=format");
		}

	} 
            else{
                    String head = request.getHeader("Referer");
                    if(head.contains("?")){
                        head=head.substring(0,head.indexOf("?"));
                    }
                    Cookie lockoutCookie = new Cookie("lockout", "0");
                    response.addCookie(lockoutCookie);
                    
                    String user = request.getParameter("name");
                    if(fhandle.getFarmer(user)!=null){
                    fhandle.toggleLockout(true, user);
                    
			response.sendRedirect(head+"?login=lockedout");
                    }else{
                        response.sendRedirect(head+"?login=noexist");
                    }
                    }
        }


	/**
         * Does nothing.
         * 
         * @param request servlet request
         * @param response servlet response
         * @throws ServletException if a servlet-specific error occurs
         * @throws IOException if an I/O error occurs
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
